package com.wigem.fa.controller;

import com.wigem.approve.vo.DaqPolicyVo;
import com.wigem.fa.dto.ApplyAndEntInfoDto;
import com.wigem.fa.dto.ApplySummaryDto;
import com.wigem.fa.entity.FaEntInfoEntity;
import com.wigem.fa.entity.ResultTable;
import com.wigem.fa.service.FaEntInfoService;
import com.wigem.fa.vo.FaSupervisorVo;
import com.wigem.framework.common.pojo.PageResult;
import com.wigem.framework.common.util.web.response.Result;
import com.wigem.framework.common.util.web.response.ResultController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wigem.fa.entity.FaApplyEntity;
import com.wigem.fa.service.FaApplyService;
import com.wigem.fa.vo.FaApplyVo;
import com.wigem.framework.operate.log.core.annotations.OperateLog;
import com.wigem.framework.operate.log.core.enums.OperateTypeEnum;
import com.wigem.framework.sa.token.core.annotation.IgnoreAuth;
import com.wigem.module.general.entity.AssistNoticeEntity;
import com.wigem.module.general.vo.AssistNoticeVo;
import com.wigem.system.entity.SystemUserEntity;
import com.wigem.system.service.SystemUserService;
import com.zqlian.sdk.data.center.common.credential.Credential;
import com.zqlian.sdk.data.center.common.exception.ZqlianSdkException;
import com.zqlian.sdk.data.center.common.profile.ClientProfile;
import com.zqlian.sdk.data.center.common.profile.HttpProfile;
import com.zqlian.sdk.data.center.common.utils.HttpMethod;
import com.zqlian.sdk.data.center.gateway.ApiGatewayRequest;
import com.zqlian.sdk.data.center.gateway.ApiGatewaySdkClient;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;

import static com.wigem.fa.controller.ResultsController.pageTable;

/**
 * 企业申报Controller
 *
 * @author DH
 * @date 2024-10-20
 */
@RestController
@RequestMapping("/fa/apply")
public class FaApplyController extends ResultController {


    @Resource
    private FaApplyService faApplyService;
    @Resource
    private FaEntInfoService faEntInfoService;
    /**
     * 查询企业申报列表
     */
    @ResponseBody
    @GetMapping("/query")
    public Result getList(FaApplyVo faApplyVo) {
        return success(faApplyService.getList(faApplyVo));
    }

    /**
     * 查询企业申报列表
     */
    @ResponseBody
    @GetMapping("/query/page")
    public Result getPageList(FaApplyVo faApplyVo) {
        PageResult<FaApplyEntity> pageInfo = faApplyService.getPageList(faApplyVo);
        return success(pageInfo);
    }
    /**
     * 查询通知通告列表
     */
    @ResponseBody
    @GetMapping("/notice/query/page")
    public Result getNoticePageList(AssistNoticeVo vo) {
        PageResult<AssistNoticeEntity> pageInfo = faApplyService.getNoticePageList(vo);
        return success(pageInfo);
    }

    @ResponseBody
    @PostMapping("/notice/save")
    public Result noticeSave(@RequestBody AssistNoticeVo vo) {
        return faApplyService.noticeSave(vo);
    }
    /**
     * 查询企业申报列表
     */
    @ResponseBody
    @GetMapping("/manage/query/page")
    public Result getManagePageList(FaApplyVo faApplyVo) {
        PageResult<ApplyAndEntInfoDto> pageInfo = faApplyService.getManagePageList(faApplyVo);
        return success(pageInfo);
    }


    /**
     * 查询事中企业申报列表
     */
    @ResponseBody
    @GetMapping("/mid/query/page")
    public Result getMidPageList(FaApplyVo faApplyVo) {
        PageResult<ApplyAndEntInfoDto> pageInfo = faApplyService.getMidPageList(faApplyVo);
        return success(pageInfo);
    }

    /**
     * 查询事后企业申报列表
     */
    @ResponseBody
    @GetMapping("/post/query/page")
    public Result getPostPageList(FaApplyVo faApplyVo) {
        PageResult<ApplyAndEntInfoDto> pageInfo = faApplyService.getPostPageList(faApplyVo);
        return success(pageInfo);
    }
    /**
     * 查询企业申报列表
     */
    @ResponseBody
    @GetMapping("/summary/query/page")
    public ResultTable getSummaryPageList(FaApplyVo faApplyVo) {
        PageResult<ApplySummaryDto> pageInfo = faApplyService.getSummaryPageList(faApplyVo);
        ApplySummaryDto totalRow = faApplyService.getTotalRow(faApplyVo);
        return pageTable(pageInfo.getList(), totalRow, pageInfo.getTotal());
    }

    /**
     * 查询企业申报实体
     */
    @ResponseBody
    @GetMapping("/query/{id}")
    public Result getEntity(@PathVariable("id") String id) {
        return success(faApplyService.getEntity(id));
    }

    @ResponseBody
    @GetMapping("/back/{id}")
    public Result back(@PathVariable("id") String id) {
        return faApplyService.back(id);
    }

    @ResponseBody
    @GetMapping("/query/dto")
    public Result queryDto(FaApplyVo faApplyVo) {
        return success(faApplyService.queryDto(faApplyVo));
    }

    /**
     * 企业申报新增
     */
    @ResponseBody
    @PostMapping("/add")
    public Result add(@RequestBody FaApplyVo faApplyVo) {
        return faApplyService.add(faApplyVo);
    }

    /**
     * 企业申报修改
     */
    @ResponseBody
    @PutMapping
    public Result update(@RequestBody FaApplyVo faApplyVo) {
        faApplyService.update(faApplyVo);
        return success("修改成功");
    }

    /**
     * 新增保存
     */
    @ResponseBody
    @PostMapping("/save")
    public Result save(@RequestBody FaApplyVo faApplyVo) {
        return faApplyService.save(faApplyVo);
    }

    /**
     * 企业提交
     */
    @ResponseBody
    @PostMapping("/commit")
    public Result commit(@RequestBody FaApplyVo faApplyVo) {
        return faApplyService.commit(faApplyVo);
    }

    /**
     * 延期申请提交
     */
    @ResponseBody
    @PostMapping("/postPone/submit")
    public Result postPoneSubmit(@RequestBody FaApplyVo faApplyVo) {
        return faApplyService.postPoneSubmit(faApplyVo);
    }



    /**
     * 管理端审批
     */
    @ResponseBody
    @PostMapping("/approve")
    public Result approve(@RequestBody FaApplyVo faApplyVo) {
        return faApplyService.approve(faApplyVo);
    }

    /**
     * 删除
     */
    @ResponseBody
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id) {
        faApplyService.delete(id);
        return success("删除成功！");
    }

    /**
     * 移除/逻辑删除
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") String id) {
        faApplyService.remove(id);
        return success("删除成功！");
    }
    @IgnoreAuth
    @ResponseBody
    @GetMapping("/jingceTest2")
    public Result jingceTest2() {
        // 设置客户端配置
        ClientProfile clientProfile = new ClientProfile();
        //测试：103.83.44.92:8443
        //正式：103.83.44.92
        clientProfile.setDomain("172.26.64.155:8080");
        clientProfile.setPrefixPath("/mp/api-gw-server/v1");
        clientProfile.setDebug(false);// 设置是否输出请求和响应相关信息以及SDK配置信息，默认false
        clientProfile.setDebugSSL(false);//设置是否忽略证书。默认false。建议仅在本地调试时设置为true
        // 设置请求相关默认配置
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setProtocol(HttpProfile.REQ_HTTP);//更改请求协议。默认Http
        httpProfile.setRequestMethod(HttpMethod.GET.name());// 更改默认请求方法。默认GET
        httpProfile.setConnectTimeoutSec(3);//设置连接超时，单位秒。默认3。0为无限等待，不能小于0。
        httpProfile.setReadTimeoutSec(3);//设置读超时，单位秒。默认3。0为无限等待，不能小于0。
        httpProfile.setWriteTimeoutSec(3);//设置写超时，单位秒。默认3。0为无限等待，不能小于0。
        clientProfile.setHttpProfile(httpProfile);
        // 测试环境：
        //AccessKey：Ki3vfj986r
        //AccessSecret：IPBQ0N1AMm1xZKFm
        //正式环境：
        //AccessKey：oonnV2kTJ2
        //AccessSecret：aa53YZxQpqwgf5OY
        Credential credential = new Credential();

        credential.setAccessKey("oonnV2kTJ2");
        credential.setAccessSecret("aa53YZxQpqwgf5OY");
        // apiVersion没有则可以不指定
        ApiGatewaySdkClient client = new ApiGatewaySdkClient("v1.0", credential, clientProfile);

        FaApplyVo faApplyVo=new FaApplyVo();
        faApplyVo.setApproveId("2");
        faApplyVo.setRemoveMark("0");
        List<FaApplyEntity> list = faApplyService.getList(faApplyVo);
        //组装请求
        Map<String, Object> param = new HashMap<>();

        param.put("batchNo", "report2024");//当前报告期
        param.put("dataSize", 7);
        param.put("reportTime", "20241021145305");

        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> dataItem = new HashMap<>();



        for (FaApplyEntity faApplyEntity : list) {
            dataItem = new HashMap<>();
            dataItem.put("requestId", faApplyEntity.getId());//申请ID
            dataItem.put("requestName", faApplyEntity.getProjectName());//项目名称
            dataItem.put("projectId", faApplyEntity.getPolicyType());//政策类型
            dataItem.put("regionCode", "110105");
            dataItem.put("applyerDate", faApplyEntity.getSubmitTime());
            dataItem.put("applyerMoney", faApplyEntity.getProposalFund());
            dataItem.put("requestState", "new");
            dataItem.put("fromData", "项目介绍："+faApplyEntity.getProjectIntroduction());
            dataItem.put("applyerType", "1");//法人
            FaEntInfoEntity entity = faEntInfoService.getEntity(faApplyEntity.getEntId());
            dataItem.put("applyeyName", entity.getOrgName());
            dataItem.put("applyerPageType","001");//类型：社会信用代码
            dataItem.put("applyerPageCode", entity.getSocialCreditCode());//社会信用代码
            dataItem.put("cdOperation", "I");
            dataList.add(dataItem);
       }
        param.put("data", dataList);
        //测试：cLpkrGnmKA  生产：d0gTFl1HLW
        String serviceId="d0gTFl1HLW";
        ApiGatewayRequest request = new ApiGatewayRequest(param, serviceId);
        request.setRequestId("");// 请求ID，可以不指定，使用客户端自动生成的requestId
        try {
            //用法1：直接获取json字符串
            String exchange = client.exchange(request, HttpMethod.POST);// 单独指定HttpMethod
            System.out.println(exchange);
        } catch (ZqlianSdkException e) {
            throw new RuntimeException(e);
        }
        return success("成功！");
    }

    @IgnoreAuth
    @ResponseBody
    @GetMapping("/jingceTest1")
    public Result jingceTest1() {

        // 设置客户端配置
        ClientProfile clientProfile = new ClientProfile();
        //测试：172.26.64.155:8081
        //正式：172.26.64.155:8080
        clientProfile.setDomain("172.26.64.155:8080");
        clientProfile.setPrefixPath("/mp/api-gw-server/v1");
        clientProfile.setDebug(false);// 设置是否输出请求和响应相关信息以及SDK配置信息，默认false
        clientProfile.setDebugSSL(false);//设置是否忽略证书。默认false。建议仅在本地调试时设置为true
        // 设置请求相关默认配置
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setProtocol(HttpProfile.REQ_HTTP);//更改请求协议。默认Http
        httpProfile.setRequestMethod(HttpMethod.GET.name());// 更改默认请求方法。默认GET
        httpProfile.setConnectTimeoutSec(3);//设置连接超时，单位秒。默认3。0为无限等待，不能小于0。
        httpProfile.setReadTimeoutSec(3);//设置读超时，单位秒。默认3。0为无限等待，不能小于0。
        httpProfile.setWriteTimeoutSec(3);//设置写超时，单位秒。默认3。0为无限等待，不能小于0。
        clientProfile.setHttpProfile(httpProfile);
        // 测试环境：
        //AccessKey：Ki3vfj986r
        //AccessSecret：IPBQ0N1AMm1xZKFm
        //正式环境：
        //AccessKey：oonnV2kTJ2
        //AccessSecret：aa53YZxQpqwgf5OY
        Credential credential = new Credential();

        credential.setAccessKey("oonnV2kTJ2");
        credential.setAccessSecret("aa53YZxQpqwgf5OY");
        // apiVersion没有则可以不指定
        ApiGatewaySdkClient client = new ApiGatewaySdkClient("v1.0", credential, clientProfile);

        //组装请求
        Map<String, Object> param = new HashMap<>();

        param.put("batchNo", "report2024");//当前报告期
        param.put("dataSize", 8);
        param.put("reportTime", "20241021145305");

        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> dataItem = new HashMap<>();


        for (int i = 1; i <= 8; i++){

            dataItem = new HashMap<>();
            dataItem.put("projectId", i);//政策类型
            dataItem.put("projectYear", 2024);//政策类型
            dataItem.put("projectName", getPolicyTypeName(i));//政策类型
            dataItem.put("regionCode", "110105");
            dataItem.put("regionName", "朝阳区");
            dataItem.put("orgCode", "11110105666280563Q");
            dataItem.put("orgName", "中关村科技园区朝阳园管理委员会");
            dataItem.put("publishDate", "20241101000000");
            dataItem.put("startDate", "20241101000000");
            dataItem.put("endDate", "20241108170000");
            dataItem.put("toward", "1");//申报主体类型
            dataItem.put( "projectUrls", "http://219.141.252.163:8080/fund");
            dataItem.put( "projectMobileUrl", "http://219.141.252.163:8080/fund");
            dataItem.put( "cdOperation", "I");
            dataList.add(dataItem);
        }
        param.put("data", dataList);
        //测试：9VtOGHlUMu   生产：sMjhOFfQ2f
        String serviceId="sMjhOFfQ2f";
        ApiGatewayRequest request = new ApiGatewayRequest(param, serviceId);
        request.setRequestId("");// 请求ID，可以不指定，使用客户端自动生成的requestId
        try {
            //用法1：直接获取json字符串
            String exchange = client.exchange(request, HttpMethod.POST);// 单独指定HttpMethod
            System.out.println(exchange);
        } catch (ZqlianSdkException e) {
            throw new RuntimeException(e);
        }
        return success("成功！");
    }

    public static String getPolicyTypeName(int typeId) {
        switch (typeId) {
            case 1:
                return "方向一：支持科技总部生态体系建设";
            case 2:
                return "方向二：支持企业核心技术攻关与首创产品创新";
            case 3:
                return "方向三：支持协同创新发展";
            case 4:
                return "方向四：支持社会发展科技创新";
            case 5:
                return "方向五：支持专业服务机构集聚产业效能";
            case 6:
                return "方向六：支持开展软课题研究";
            case 7:
                return "方向七：支持高校、科研院所与企业开展成果转化活动";
            case 8:
                return "方向八：参与北京市自然科学基金联合基金—朝阳基金";
            default:
                return "未知方向";
        }
    }


    @ResponseBody
    @GetMapping("/zip/file")
    @OperateLog(name = "科技计划项目申报", type = OperateTypeEnum.GET, module = "科技计划项目申报")
    public void exportPolicy(HttpServletResponse httpServletResponse, FaApplyVo faApplyVo) throws Exception {
        faApplyService.exportApply(httpServletResponse,faApplyVo);
    }
}
